package traditional.thread.communicate;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 完全复制张孝祥的思路
 * 经过思考后发现：如果不用wait notify,也不用condition,事实上main方法是不会将cpu控制权交出去的，它会一直在搞，这样
 * 虽然实现了互斥，但是不会你一下我一下了
 * @author Germmy
 *
 */
public class ThreelNewTheadLockTestZxxWithCommunicate {

	

	public static void main(String[] args) {


		final Business business=new Business();
			new Thread(new Runnable() {
				public void run() {
					// 整体循环50次
					for (int i = 0; i < 50; i++) {
						// 大哥来搞100次
						business.main(i);
					}

				}
			}).start();

			new Thread(new Runnable() {

				public void run() {
					// 整体循环50次
					for (int i = 0; i < 50; i++) {
						// 小弟2来搞10次
						business.sub2(i);
					}

				}
			}).start();
			
			
			new Thread(new Runnable() {

				public void run() {
					// 整体循环50次
					for (int i = 0; i < 50; i++) {
						// 小弟3来搞20次
						business.sub3(i);
					}

				}
			}).start();



	}

	
	 
	 
	 static class Business{
		 int isShould = 1;
		 Lock lock=new ReentrantLock();
		 Condition condition1=lock.newCondition();
		 Condition condition2=lock.newCondition();
		 Condition condition3=lock.newCondition();
		 void main(int ii) {
			 	lock.lock();
			 	try{
			 		while (isShould!=1) {
			 			try {
			 				condition1.await();
			 			} catch (Exception e) {
			 				// TODO Auto-generated catch block
			 				e.printStackTrace();
			 			}
			 		}
			 		for (int i = 0; i < 100; i++) {
			 			System.out.println("main:" + i+",loop of "+ii);
			 		}
			 		isShould = 2;
			 		condition2.signal();
			 	}finally{
			 		lock.unlock();
			 	}
			}

			 void sub2(int ii) {
				 lock.lock();
				 try{
					 while (isShould!=2) {
						 try {
							 condition2.await();
						 } catch (Exception e) {
							 // TODO Auto-generated catch block
							 e.printStackTrace();
						 }	
					 }
					 for (int i = 0; i < 10; i++) {
						 System.out.println("sub2:" +  i+",loop of "+ii);
					 }
					 isShould = 3;
					 condition3.signal();
				 }finally{
					 lock.unlock();
				 }
			}
			 
			 
			 
			 void sub3(int ii) {
				 lock.lock();
				 try{
					 while (isShould!=3) {
						 try {
							 condition3.await();
						 } catch (Exception e) {
							 // TODO Auto-generated catch block
							 e.printStackTrace();
						 }	
					 }
					 for (int i = 0; i < 20; i++) {
						 System.out.println("sub3:" + i+",loop of "+ii);
					 }
					 isShould=1;
					 condition1.signal();
				 }finally{
					 lock.unlock();
				 }
			}
			 
	 }
	 
	 
	 
	 

}
